import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Layout,
  Button,
  Space,
  message,
  Tooltip,
  FloatButton
} from 'antd';
import {
  MenuOutlined,
  PlusOutlined,
  DownOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import MessageBubble from '../components/MessageBubble';
import MessageInput from '../components/MessageInput';
import SessionSidebar from '../components/SessionSidebar';
import TypingIndicator from '../components/TypingIndicator';
import { chatAPI } from '../services/api';
import './ChatPage.css';

const { Content } = Layout;

const ChatPage = () => {
  const { sessionId: urlSessionId } = useParams();
  const navigate = useNavigate();
  
  // 状态管理
  const [messages, setMessages] = useState([]);
  const [currentSessionId, setCurrentSessionId] = useState(null);
  const [loading, setLoading] = useState(false);
  const [sidebarVisible, setSidebarVisible] = useState(false);
  const [isTyping, setIsTyping] = useState(false);
  const [sessionInfo, setSessionInfo] = useState(null);
  
  // 引用
  const messagesEndRef = useRef(null);
  const messagesContainerRef = useRef(null);

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 检查是否需要显示滚动到底部按钮
  const [showScrollButton, setShowScrollButton] = useState(false);
  
  const handleScroll = () => {
    if (messagesContainerRef.current) {
      const { scrollTop, scrollHeight, clientHeight } = messagesContainerRef.current;
      const isNearBottom = scrollHeight - scrollTop - clientHeight < 100;
      setShowScrollButton(!isNearBottom && messages.length > 0);
    }
  };

  // 创建新会话
  const createNewSession = async () => {
    try {
      const response = await chatAPI.createNewSession();
      const newSessionId = response.session_id;
      
      setCurrentSessionId(newSessionId);
      setMessages([]);
      setSessionInfo(null);
      
      // 更新URL
      navigate(`/chat/${newSessionId}`, { replace: true });
      
      message.success('已创建新对话');
      return newSessionId;
    } catch (error) {
      console.error('创建新会话失败:', error);
      message.error('创建新会话失败');
      return null;
    }
  };

  // 加载会话消息
  const loadSessionMessages = async (sessionId) => {
    if (!sessionId) return;
    
    try {
      setLoading(true);
      const response = await chatAPI.getSessionMessages(sessionId);
      
      // 转换消息格式
      const formattedMessages = response.messages.map(msg => ({
        id: msg.id,
        content: msg.content,
        type: msg.type,
        timestamp: msg.timestamp,
        confidence_score: msg.confidence_score,
        isUser: msg.type === 'user'
      }));
      
      setMessages(formattedMessages);
      setCurrentSessionId(sessionId);
      
      // 获取会话摘要信息
      try {
        const summaryResponse = await chatAPI.getSessionSummary(sessionId);
        setSessionInfo(summaryResponse);
      } catch (summaryError) {
        console.warn('获取会话摘要失败:', summaryError);
      }
      
    } catch (error) {
      console.error('加载会话消息失败:', error);
      message.error('加载会话消息失败');
      
      // 如果会话不存在，创建新会话
      if (error.response?.status === 404) {
        createNewSession();
      }
    } finally {
      setLoading(false);
    }
  };

  // 发送消息
  const handleSendMessage = async (messageContent) => {
    if (!messageContent.trim()) return;

    // 添加用户消息到界面
    const userMessage = {
      id: Date.now(),
      content: messageContent,
      type: 'user',
      timestamp: new Date().toISOString(),
      isUser: true
    };
    
    setMessages(prev => [...prev, userMessage]);
    setIsTyping(true);

    try {
      // 发送消息到后端
      const response = await chatAPI.sendMessage(
        messageContent, 
        currentSessionId
      );

      // 添加AI回复到界面
      const aiMessage = {
        id: Date.now() + 1,
        content: response.response,
        type: 'assistant',
        timestamp: new Date().toISOString(),
        confidence_score: response.confidence_score,
        has_safety_warning: response.has_safety_warning,
        safety_info: response.safety_info,
        isUser: false
      };

      setMessages(prev => [...prev, aiMessage]);
      
      // 更新当前会话ID（如果是新会话）
      if (response.session_id !== currentSessionId) {
        setCurrentSessionId(response.session_id);
        navigate(`/chat/${response.session_id}`, { replace: true });
      }

    } catch (error) {
      console.error('发送消息失败:', error);
      message.error('发送消息失败，请重试');
      
      // 移除用户消息
      setMessages(prev => prev.filter(msg => msg.id !== userMessage.id));
    } finally {
      setIsTyping(false);
    }
  };

  // 选择会话
  const handleSessionSelect = (sessionId) => {
    if (sessionId !== currentSessionId) {
      navigate(`/chat/${sessionId}`);
    }
  };

  // 初始化
  useEffect(() => {
    if (urlSessionId) {
      loadSessionMessages(urlSessionId);
    } else {
      createNewSession();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [urlSessionId]);

  // 自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages, isTyping]);

  return (
    <Layout className="chat-page">
      {/* 顶部工具栏 */}
      <div className="chat-toolbar">
        <Space>
          <Button
            icon={<MenuOutlined />}
            onClick={() => setSidebarVisible(true)}
          >
            对话历史
          </Button>

          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={createNewSession}
          >
            新对话
          </Button>

          {sessionInfo && (
            <Tooltip title={`消息数: ${sessionInfo.statistics?.message_count || 0}`}>
              <Button
                icon={<InfoCircleOutlined />}
                type="text"
              >
                会话信息
              </Button>
            </Tooltip>
          )}
        </Space>
      </div>

      {/* 消息区域 */}
      <Content className="chat-content">
        <div
          className="messages-container"
          ref={messagesContainerRef}
          onScroll={handleScroll}
        >
          <div className="messages-list">
            {messages.length === 0 && !loading && (
              <div className="welcome-message">
                <h2>👋 欢迎使用系统操作助手</h2>
                <p>我是您的智能助手，可以帮您解答各种系统操作问题。</p>
                <p>请输入您的问题，我会为您提供详细的操作指导。</p>
              </div>
            )}

            {messages.map((message) => (
              <MessageBubble
                key={message.id}
                message={message}
                isUser={message.isUser}
              />
            ))}

            {isTyping && <TypingIndicator />}

            <div ref={messagesEndRef} />
          </div>
        </div>

        {/* 输入区域 */}
        <div className="input-container">
          <MessageInput
            onSendMessage={handleSendMessage}
            loading={isTyping}
            disabled={loading}
          />
        </div>
      </Content>

      {/* 滚动到底部按钮 */}
      {showScrollButton && (
        <FloatButton
          icon={<DownOutlined />}
          onClick={scrollToBottom}
          style={{ right: 24, bottom: 100 }}
          tooltip="滚动到底部"
        />
      )}

      {/* 会话侧边栏 */}
      <SessionSidebar
        visible={sidebarVisible}
        onClose={() => setSidebarVisible(false)}
        currentSessionId={currentSessionId}
        onSessionSelect={handleSessionSelect}
        onNewSession={createNewSession}
      />
    </Layout>
  );
};

export default ChatPage;
